//
//  MKSystemPreviewVideoCollectionViewCell.swift
//  MKImageBrowser3
//
//  Created by 劢克科技 on 2019/5/14.
//  Copyright © 2019 meckey. All rights reserved.
//  预览视频

import UIKit
import AVFoundation

class MKSystemPreviewVideoCollectionViewCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        playerLayer.removeFromSuperlayer()
        playButton.removeFromSuperview()
    }
    
    //MARK: - Setter
    
    func setVideoUrl(url: URL) {
        self.url = url
        initVideo()
    }
    
    func pause() {
        player.pause()
        playButton.alpha = 1
    }
    
    @objc func play() {
        player.play()
        playButton.alpha = 0
    }
    
    //MARK: - Getter
    
    fileprivate var url: URL!
    fileprivate var asset: AVAsset!
    fileprivate var player: AVPlayer!
    fileprivate var playerItem: AVPlayerItem!
    fileprivate var playerLayer: AVPlayerLayer!
    fileprivate var timeObserverToken: Any?
    
    lazy var playButton: UIImageView = {
        let imageV = UIImageView(image: #imageLiteral(resourceName: "playVideo"))
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        imageV.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: #selector(play))
        gesture.numberOfTapsRequired = 1
        gesture.numberOfTouchesRequired = 1
        imageV.addGestureRecognizer(gesture)
        return imageV
    }()
    
    //MARK: - Initials
    
    fileprivate func initVideo() {
        asset = AVAsset(url: url)
        playerItem = AVPlayerItem(asset: asset)
        player = AVPlayer(playerItem: playerItem)
        playerLayer = AVPlayerLayer(player: player)
        
        contentView.layer.addSublayer(playerLayer)
        playerLayer.frame = contentView.bounds
        
        contentView.addSubview(playButton)
        playButton.snp.makeConstraints { (make) in
            make.center.equalTo(contentView.snp_center)
            make.width.equalTo(80)
            make.height.equalTo(80)
        }
    }
    
    
}
